<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxePagerEvents } from 'vxe-table'

import { Search } from '@element-plus/icons-vue'
import { getDeptTree, getUserRoleList, useGetUserList, useUserDel, useUserExport } from '@fl/api/iam-api/user-manage'
import { SearchForm, SearchTable } from '@fl/components'
import { formatTime } from '@fl/utils'
import { cloneDeep } from 'lodash-es'

import addOrEdit from './component/add-or-edit.vue'
import resetCodeBox from './component/resetCodeBox.vue'
import roleList from './component/role-list.vue'
import { TextDict, TypeDict } from './constant'

const tableRef = ref()
const treeRef = ref()
const isTrue = ref(true)
const treeData = ref<any>([])
const roleOptions = ref<any>([])
const resetCodeVisible = ref<boolean>(false)
const resetCodeUserId = ref<string>('')
const resetCodeUserName = ref<string>('')
const records = ref<any>()
const editVisible = ref<boolean>(false)
const editId = ref<string>('')
const activeTreeId = ref<number>()
const filterText = ref<string>('')
const roleListVisible = ref<boolean>(false)
const roleRow = ref<any>() //当前角色信息

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

// 搜索条件、分页参数
type RequestIndex = {
    createTime: any
    deptId?: number
    params?: any
    phonenumber?: string
    status?: string // 0正常 1停用
    userName?: string
}
const initialState = {
    createTime: ['', ''],
    deptId: undefined,
    params: {}, // beginTime, endTime?
    phonenumber: '',
    status: '',
    userName: '',
}
const state = ref<RequestIndex>(cloneDeep(initialState))
const { mutate: delMutate } = useUserDel()

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))

const params = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    ...state.value,
    createTime: null,
    params: {
        beginTime: state.value.createTime?.[0] ? formatTime(state.value?.createTime[0], 'yyyy-MM-dd 00:00:00') : null,
        endTime: state.value.createTime?.[1] ? formatTime(state.value?.createTime[1], 'yyyy-MM-dd 23:59:59') : null,
    },
}))
const { data, isLoading } = useGetUserList(params)
watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.rows)
        tablePage.value.total = data.value.total!
    }
})

const exportParams = computed(() => ({
    deptId: state.value.deptId,
    phonenumber: state.value.phonenumber,
    status: state.value.status,
    userName: state.value.userName,
    params: {
        beginTime: state.value.createTime?.[0] ? formatTime(state.value?.createTime[0], 'yyyy-MM-dd 00:00:00') : null,
        endTime: state.value.createTime?.[1] ? formatTime(state.value?.createTime[1], 'yyyy-MM-dd 23:59:59') : null,
    },
}))
// 导出
const { mutateAsync } = useUserExport(exportParams)
async function exportData() {
    const res = await mutateAsync()
    if (res) {
        const objectUrl = URL.createObjectURL(res)
        location.href = objectUrl
        URL.revokeObjectURL(objectUrl)
    }
}

const defaultProps = {
    children: 'children',
    label: 'label',
}

// 点击机构树
function handleNodeClick(data: any) {
    state.value.deptId = data.id
    activeTreeId.value = data.id
}

// 部门树
function getTreeData() {
    getDeptTree({}).then((res) => {
        treeData.value = res
        console.log('getTreeData', res, activeTreeId.value)
    })
}

function getRoleData() {
    getUserRoleList({}).then((res) => {
        console.log('getRoleData', res)
        roleOptions.value = cloneDeep(res.data.roles).reduce((pre, cur) => {
            cur.value = cur.roleId
            cur.label = cur.roleName
            pre.push(cur)
            return pre
        }, [])
    })
}

init()
function init() {
    getTreeData()
    getRoleData()
}

// 搜索
function submit(values: RequestIndex) {
    state.value = { ...values }
    state.value.deptId = activeTreeId.value
}

// 重置
function reset() {
    state.value = cloneDeep(initialState)
    filterText.value = ''
    activeTreeId.value = undefined
}

// 新增
function goToAdd() {
    editVisible.value = true
}

// 编辑
function goToEdit(row: any) {
    editVisible.value = true
    editId.value = String(row.userId)
}

// 重置密码
function goToResetPwd(row: any) {
    console.log('row', row)
    resetCodeVisible.value = true
    resetCodeUserId.value = String(row.userId)
    resetCodeUserName.value = row.userName
}

// 分配角色
function distributeRole(row: any) {
    console.log('分配角色', row)
    roleRow.value = row
    roleListVisible.value = true
}

function goToDel(row: any) {
    delMutate(row.userId, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

function filterNode(value: string, data: any) {
    if (!value)
        return true
    return data.label.includes(value)
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

const AuthOption = [
    {
        label: '正常',
        value: '0',
    },
    {
        label: '停用',
        value: '1',
    },
]

const columns: PlusColumn[] = [
    {
        label: '登录名称',
        prop: 'userName',
        valueType: 'copy',
    },
    {
        label: '手机号码',
        prop: 'phonenumber',
        valueType: 'copy',
    },
    {
        label: '账号状态',
        options: AuthOption,
        prop: 'status',
        valueType: 'select',
    },
    {
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
        },
        label: '创建时间',
        prop: 'createTime',
        valueType: 'date-picker',
    },
]

const gridOptions = reactive({
    columns: [
        { title: '序号', type: 'seq', width: 50 },
        { field: 'userName', title: '登录名称' },
        { field: 'nickName', title: '用户名称' },
        { field: 'email', title: '用户邮箱' },
        { field: 'phonenumber', title: '手机号' },
        { field: 'status', slots: { default: 'status' }, title: '账号状态', width: 80 },
        { field: 'createTime', title: '创建时间' },
        { slots: { default: 'operate' }, title: '操作', width: 260 },
    ],
})
</script>

<template>
    <div flex
         justify-between
    >
        <ElCard style="width:20%">
            <ElInput v-model="filterText"
                     class="mb20"
                     :prefix-icon="Search"
                     clearable
                     placeholder="请输入部门名称"
            />

            <ElTree ref="treeRef"
                    style="max-width: 600px"
                    :data="treeData"
                    :props="defaultProps"
                    node-key="id"
                    :filter-node-method="filterNode"
                    :default-expand-all="isTrue"
                    :highlight-current="isTrue"
                    :expand-on-click-node="isTrue"
                    :current-node-key="activeTreeId"
                    @node-click="handleNodeClick($event)"
            />
        </ElCard>

        <ElCard style="width:80%"
                ml-20
        >
            <ElCard class="mb-20">
                <SearchForm v-bind="state"
                            :columns="columns"
                            submit-text="搜索"
                            @reset="reset"
                            @submit="submit"
                />
            </ElCard>

            <ElCard>
                <ElButton type="primary"
                          @click="goToAdd"
                >
                    +新增
                </ElButton>

                <ElButton type="primary"
                          plain
                          @click="exportData"
                >
                    导出
                </ElButton>

                <SearchTable ref="tableRef"
                             v-bind="gridOptions"
                             v-model:pager="tablePage"
                             :loading="isLoading"
                             :data="records"
                             @page-change="handlePageChange"
                >
                    <template #status="{ row }">
                        <div style="cursor: pointer;">
                            <ElTag :type="TypeDict[row.status]">
                                {{ TextDict[row.status] }}
                            </ElTag>
                        </div>
                    </template>

                    <template #operate="{ row }">
                        <div v-if="row.userId !== 1">
                            <el-button class="small"
                                       type="primary"
                                       text
                                       @click="goToEdit(row)"
                            >
                                编辑
                            </el-button>

                            <el-button class="small"
                                       text
                                       @click="goToResetPwd(row)"
                            >
                                重置密码
                            </el-button>

                            <el-button class="small"
                                       type="primary"
                                       text
                                       @click="distributeRole(row)"
                            >
                                分配角色
                            </el-button>

                            <el-popconfirm title="确认删除吗？"
                                           @confirm="goToDel(row)"
                            >
                                <template #reference>
                                    <el-button class="small"
                                               text
                                               type="warning"
                                    >
                                        删除
                                    </el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                    </template>
                </SearchTable>
            </ElCard>
        </ElCard>
    </div>

    <addOrEdit v-model:visible="editVisible"
               v-model:id="editId"
               :roleOptions="roleOptions"
               :treeData="treeData"
    />

    <resetCodeBox v-model:visible="resetCodeVisible"
                  v-model:userid="resetCodeUserId"
                  v-model:username="resetCodeUserName"
    />

    <roleList v-model:show="roleListVisible" :roleRow="roleRow" :roleOptions="roleOptions"  />
</template>

<style lang="scss" scoped>
:deep(.small.el-button) {
    padding: 4px;
    margin-left: 6px;
}
</style>
